import axios from "axios";
import { Store } from 'le5le-store';

// 后端基础路由
// export const baseUrl = "http://59.67.246.128:5900";
export const baseUrl = "http://localhost:5000";

// 配置跨域访问 Header 字段
axios.defaults.headers.common['Access-Control-Allow-Credentials'] = true;

// 前端发送 Get 请求
export const axiosGetFunction = (url, onFinishData, onFail, onErr) => {
    // 设置 withCredentials 解决跨域问题
    axios.get(baseUrl + url, { withCredentials: false })
        .then((res)=>{
            if (res.data) {
                let {success, data} = res.data;
                if (success && success === true){
                    if (onFinishData){
                        onFinishData(data);
                    }
                }else {
                    if (onFail) onFail(data);
                }
            }
        })
        .catch((err)=>{
            console.error(err);
            if (onErr) onErr();
        });
}

// 前端发送 Post 请求
export const axiosPostFunction = (url, data, onFinishData, onFail, onErr) => {
    axios.post(baseUrl + url, data)
        .then((res)=>{
            console.log("axiosPostFunction: received: ", res);
            if (res.data){
                let {data, success} = res.data;
                if (success && success === true){
                    if (onFinishData) onFinishData(data);
                }else {
                    if (onFail) onFail(data);
                }
            }
        })
        .catch((err)=>{
            console.log(err);
            if (onErr) onErr(err);
        })
}

// 预览的时候向 Store 当中新添加一个字段
export const addNewRuleToStore = (newRule) => {
    let listenList = Store.get("listenList");
    if (listenList != null){
        listenList.append(newRule);
        Store.set("listenList", listenList);
    }
    else {
        Store.set("listenList", [newRule, ]);
    }
}

// 判断一个字符串或者文本域能否被解析
export const parseToJsonObj = (inputStr) => {
    try {
        let res = JSON.parse(inputStr);
        return {
            success: true,
            res,
        }
    }catch (e){
        console.error("Error: AppConfig.js: parseToJsonObj: ", e)
        return {
            success: false,
        }
    }
}
